package com.zyiot.lbs;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.cloud.Bounds;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.umeng.analytics.MobclickAgent;
import com.zyiot.bdapi.LBSCloudSearch;
import com.zyiot.model.Eshop;
import com.zyiot.utils.ZyUnit;

public class TabListMapActivity extends Activity {

	MapView mMapView;
	private Context context;
	public static final int MSG_NET_TIMEOUT = 100;
	public static final int MSG_NET_STATUS_ERROR = 200;
	public static final int MSG_NET_SUCC = 1;
	private boolean initSearchFlag = false;
	BMapManager mBMapManager = null;
	private MapController mMapController = null;

	private InitApplication app = null;
	private List<Eshop> list = new ArrayList<Eshop>();

	private PopupWindow mPopupWindow;

	private String region_name;
	private String[] ArrayList_region;
	private HashMap<String, String> map_region;
	GeoPoint leftBottom;
	GeoPoint rightTop;
	Bounds bounds;

	Spinner spinner_region;
	Spinner spinner_nearby;
	Spinner spinner_tags;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (InitApplication) this.getApplication();
		mBMapManager = app.mBMapManager;
		context = this;
		setContentView(R.layout.layout_eshop_map);
		region_name = "无锡";

		initregionlist();

		initSpinner();

		initMapView();
		// 加载搜索结果
		popHandler.postDelayed(popRunnable, 500);

		Button btnRefresh = (Button) findViewById(R.id.btnrefresh);
		btnRefresh.setOnClickListener(btn_refresh_listener);

		Button btnList = (Button) findViewById(R.id.btnlist);
		btnList.setOnClickListener(btn_list_listener);

		EditText edit_search = (EditText) findViewById(R.id.edit_search);
		edit_search.setOnEditorActionListener(sumbit);
		mMapView.regMapViewListener(mBMapManager, mkmapviewlistener);

	}

	private MKMapViewListener mkmapviewlistener = new MKMapViewListener() {
		@Override
		public void onMapMoveFinish() {
			// search_Bounds();
		}
		@Override
		public void onClickMapPoi(MapPoi arg0) {
		}

		@Override
		public void onGetCurrentMap(Bitmap arg0) {
		}

		@Override
		public void onMapAnimationFinish() {
		}

		@Override
		public void onMapLoadFinish() {
		}

	};

	// 搜索回车按钮
	private OnEditorActionListener sumbit = new OnEditorActionListener() {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_SEND) {
				search();
				return true;
			}
			return false;
		}
	};

	public void showPopwindow() {
		if (mPopupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) (TabListMapActivity.this).getSystemService(LAYOUT_INFLATER_SERVICE);
			// 获取自定义布局文件poplayout.xml的视图
			View popview = layoutInflater.inflate(R.layout.progressbar, null);
			mPopupWindow = new PopupWindow(popview, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		}
		mPopupWindow.setFocusable(true);
		mPopupWindow.setTouchable(false);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 规定弹窗的位置
		View view = findViewById(R.id.btnrefresh);
		mPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
	}

	public void closePopwindow() {
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
		}
	}

	// 初始化下拉列表
	private void initSpinner() {
		spinner_region = (Spinner) findViewById(R.id.spinner_region);
		spinner_nearby = (Spinner) findViewById(R.id.spinner_nearby);
		spinner_tags = (Spinner) findViewById(R.id.spinner_tags);
		// 设置区域过滤下拉框
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.eshop_region, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_region.setAdapter(adapter);
		spinner_region.setOnItemSelectedListener(tvlist_select_region_item_listener);

		// 设置区域范围下拉框
		adapter = ArrayAdapter.createFromResource(this, R.array.eshop_nearby, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_nearby.setAdapter(adapter);
		spinner_nearby.setOnItemSelectedListener(tvlist_select_nearby_item_listener);

		// 设置商家类型下拉框
		adapter = ArrayAdapter.createFromResource(this, R.array.eshop_type, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner_tags.setAdapter(adapter);
		spinner_tags.setOnItemSelectedListener(tvlist_select_type_item_listener);

	}

	// 初始化并分割区域列表
	private void initregionlist() {
		ArrayList_region = getResources().getStringArray(R.array.eshop);
		String[] region = ZyUnit.spiltArray(ArrayList_region, "[|]", 0);
		String[] geopoint = ZyUnit.spiltArray(ArrayList_region, "[|]", 1);
		map_region = new HashMap<String, String>();
		for (int i = 0; i < region.length; i++) {
			map_region.put(region[i], geopoint[i]);
		}
	};

	// 省市搜索按钮监听
	private OnItemSelectedListener tvlist_select_region_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				//spinner_nearby.setSelection(0);
				search();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	};

	// 区域范围检索
	private OnItemSelectedListener tvlist_select_nearby_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				//spinner_region.setSelection(0);
				search();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	};

	// 商家类型检索
	private OnItemSelectedListener tvlist_select_type_item_listener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			if (initSearchFlag) {
				search();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	};

	// 地图刷新
	private OnClickListener btn_refresh_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			removeAllMarker();
			initMapView();
			search();
			InitApplication.getInstance().setHandler(mHandler);

		}
	};
	private OnClickListener btn_list_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.setClass(context, TabListActivity.class);
			intent.putExtra("list", list.toArray());
			startActivityForResult(intent, 11);
			int version = Integer.valueOf(VERSION.SDK_INT);
			if (version >= 5) {
				overridePendingTransition(R.anim.zoom_in, R.anim.zoom_out);
			}

		}
	};

	@Override
	// 建议在您app的退出之前调用mapadpi的destroy()函数，避免重复初始化带来的时间消耗
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (mBMapManager != null) {
			mBMapManager.destroy();
			mBMapManager = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		if (mBMapManager != null) {
			mBMapManager.stop();
		}
		removeAllMarker();
		super.onPause();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		if (mBMapManager != null) {
			mBMapManager.start();
		}
		super.onResume();
		MobclickAgent.onResume(this);
	}

	// 云搜索handle
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			closePopwindow();
			switch (msg.what) {
			case MSG_NET_TIMEOUT:
				break;
			case MSG_NET_STATUS_ERROR:
				break;
			case MSG_NET_SUCC:
				initSearchFlag = true;
				String result = msg.obj.toString();
				Log.d("TEST", "JSON---->" + result);
				try {
					JSONObject json = new JSONObject(result);
					// parser(json);
					parser_V2(json);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;

			}
		};

	};
	// 启动popwindow
	private Handler popHandler = new Handler();
	private Runnable popRunnable = new Runnable() {
		@Override
		public void run() {
			showPopwindow();
			search();
			// search_Bounds();
			InitApplication.getInstance().setHandler(mHandler);

		}
	};

	private void initMapView() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.setBuiltInZoomControls(true);
		// 设置启用内置的缩放控件
		MapController mMapController = mMapView.getController();
		// 得到mMapView的控制权,可以用它控制和驱动平移和缩放
		GeoPoint point = new GeoPoint((int) (31.925 * 1E6), (int) (120.292 * 1E6));
		// 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
		mMapController.setCenter(point);// 设置地图中心点
		mMapController.setZoom(14);// 设置地图zoom级别

	}

	/*
	 * 云检索发起
	 */
	private void search() {

		app.getList().clear();
		showPopwindow();
		// 云检索发起
		// LBSCloudSearch.request(getRequestParams(), mHandler,
		// initApplication.networkType);
		LBSCloudSearch.request_V2(getRequestParams_V2(), mHandler, InitApplication.networkType);
	}

	private void search_Bounds() {

		app.getList().clear();
		showPopwindow();
		// 云检索发起
			LBSCloudSearch.request_V2(getRequestParamsBounds_V2(), mHandler, InitApplication.networkType);
	}

	// 屏幕范围内搜索
	private HashMap<String, Object> getRequestParamsBounds_V2() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("TYPE", LBSCloudSearch.BOUND_CODE);
		GeoPoint mapCenter = mMapView.getMapCenter();
		// 维度范围,上下拖动时变化
		int latitudeSpan = mMapView.getLatitudeSpan();
		// 经度范围,左右拖动时变化
		int longitudeSpan = mMapView.getLongitudeSpan();
		// 屏幕左下角坐标点
		leftBottom = new GeoPoint( latitudeSpan , longitudeSpan);
		// 屏幕右上角坐标点
		rightTop = new GeoPoint(mapCenter.getLatitudeE6() + latitudeSpan , mapCenter.getLongitudeE6() + longitudeSpan );
		// 搜索手机屏幕内所需信息
		double leftBottom_lat = leftBottom.getLatitudeE6() / 1E6;
		double leftBottom_long = leftBottom.getLongitudeE6() / 1E6;
		double rightTop_lat = rightTop.getLatitudeE6() / 1E6;
		double rightTop_long = rightTop.getLongitudeE6() / 1E6;
		String bounds = leftBottom_long + "," + leftBottom_lat + ";" + rightTop_long + "," + rightTop_lat;
		
		Log.d("TEST","bounds:"+bounds);
		map.put("bounds", bounds);
		return map;

	}

	/*
	 * 获取云检索参数
	 */
	private HashMap<String, String> getRequestParams() {
		HashMap<String, String> map = new HashMap<String, String>();
		final Spinner spinner_region = (Spinner) findViewById(R.id.spinner_region);
		final Spinner spinner_nearby = (Spinner) findViewById(R.id.spinner_nearby);
		final Spinner spinner_tags = (Spinner) findViewById(R.id.spinner_tags);
		final EditText edittext_search = (EditText) findViewById(R.id.edit_search);
		try {
			String filter = "";
			map.put("region", URLEncoder.encode("无锡", "utf-8"));
			String query_str = edittext_search.getText().toString();

			// 过滤条件搜索
			if (!query_str.equals(null) && !query_str.equals("")) {
				map.put("q", query_str);
			}

			// 省市搜索
			if (spinner_region.getSelectedItemPosition() > 0) {
				String s1String = spinner_region.getSelectedItem().toString();
				map.put("region", URLEncoder.encode(s1String, "utf-8"));
			}
			// 区域范围
			if (spinner_nearby.getSelectedItemPosition() > 0) {
				String s1String = spinner_nearby.getSelectedItem().toString();
				s1String = s1String.substring(0, s1String.length() - 1);
				map.put("radius", s1String);
				if (app.currlocation != null) {
					map.put("location", app.currlocation.getLatitude() + "," + app.currlocation.getLongitude());
				} else {
					// 无定位数据默认江阴
					int cLat = 31925816;
					int cLon = 120292073;
					map.put("location", cLat + "," + cLon);
				}
			}
			// 商家类型
			if (spinner_tags.getSelectedItemPosition() > 0) {
				String s1String = spinner_tags.getSelectedItem().toString();
				map.put("tag", s1String);
			}

			map.put("filter", filter);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return map;
	}

	/*
	 * 解析返回数据
	 */
	private void parser(JSONObject json) {
		Eshop content = null;
		try {
			JSONArray jsonArray = json.getJSONArray("content");
			if (jsonArray != null && jsonArray.length() <= 0) {
				Toast.makeText(context, "该地区范围内‘E消费’联盟商家正在洽谈中，敬请期待！", Toast.LENGTH_SHORT).show();
			} else {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					content = new Eshop();
					content.setName(jsonObject2.getString("name"));
					content.setAddr(jsonObject2.getString("addr"));
					content.setDistance(jsonObject2.getString("distance"));
					double latitude = jsonObject2.getDouble("latitude");
					double longitude = jsonObject2.getDouble("longitude");
					content.setLatitude(latitude);
					content.setLongitude(longitude);

					float results[] = new float[1];

					if (app.currlocation != null) {
						Location.distanceBetween(app.currlocation.getLatitude(), app.currlocation.getLongitude(), latitude, longitude, results);
					}
					content.setDistance((int) results[0] + "米");
					JSONObject jsonObject3 = jsonObject2.optJSONObject("ext");
					if (jsonObject3 != null) {
						content.setImageurl(jsonObject3.getString("logo"));
					}

					list.add(content);
				}

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		app.setList(list);
		addAllMarker();
	}

	private HashMap<String, Object> getRequestParams_V2() {
		HashMap<String, Object> map = new HashMap<String, Object>();
		final Spinner spinner_region = (Spinner) findViewById(R.id.spinner_region);
		final Spinner spinner_nearby = (Spinner) findViewById(R.id.spinner_nearby);
		final Spinner spinner_type = (Spinner) findViewById(R.id.spinner_tags);
		final EditText edittext_search = (EditText) findViewById(R.id.edit_search);
		try {

			map.put("region", URLEncoder.encode("无锡", "utf-8"));
			map.put("TYPE", LBSCloudSearch.LOCAL_CODE);
			String query_str = edittext_search.getText().toString();
			// 过滤条件搜索
			if (!query_str.equals(null) && !query_str.equals("")) {
				map.put("q", query_str);
			}

			// 省市搜索
			if (spinner_region.getSelectedItemPosition() > 0) {
				String s1String = spinner_region.getSelectedItem().toString();
				map.put("region", URLEncoder.encode(s1String, "utf-8"));
				map.remove("TYPE");
				map.put("TYPE", LBSCloudSearch.LOCAL_CODE);
			}
			// 区域范围
			if (spinner_nearby.getSelectedItemPosition() > 0) {
				String s1String = spinner_nearby.getSelectedItem().toString();
				s1String = s1String.substring(0, s1String.length() - 1);
				map.remove("TYPE");
				map.remove("region");
				map.put("TYPE", LBSCloudSearch.NEARBY_CODE);
				map.put("radius", s1String);
				if (app.currlocation != null) {
					map.put("location", app.currlocation.getLongitude() + "," + app.currlocation.getLatitude());
				} else {
					// 无定位数据默认江阴
					double cLat = 31.925816;
					double cLon = 120.292073;
					map.put("location", cLon + "," + cLat);
				}
			}
			// 商家类型
			if (spinner_type.getSelectedItemPosition() > 0) {
				String s1String = spinner_type.getSelectedItem().toString();
				map.put("tag", s1String);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return map;
	}

	/*
	 * 解析返回数据
	 */
	private void parser_V2(JSONObject json) {
		Eshop content = null;
		try {
			JSONArray jsonArray = json.getJSONArray("contents");
			if (jsonArray != null && jsonArray.length() <= 0) {
				Toast.makeText(context, "该地区范围内‘E消费’联盟商家正在洽谈中，敬请期待！", Toast.LENGTH_SHORT).show();
			} else {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					content = new Eshop();
					content.setName(jsonObject2.getString("title"));
					content.setAddr(jsonObject2.getString("address"));
					content.setDistance(jsonObject2.getString("distance"));
					content.setImageurl(jsonObject2.optString("logo"));
					// 计算距离
					JSONArray location = jsonObject2.getJSONArray("location");
					double latitude = (Double) location.get(1);
					double longitude = (Double) location.get(0);
					content.setLatitude(latitude);
					content.setLongitude(longitude);
					float results[] = new float[1];
					if (app.currlocation != null) {
						Location.distanceBetween(app.currlocation.getLatitude(), app.currlocation.getLongitude(), latitude, longitude, results);
					}
					content.setDistance((int) results[0] + "米");
					list.add(content);
				}

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		app.setList(list);
		addAllMarker();
	}

	/**
	 * 删除所有标记
	 */
	public void removeAllMarker() {
		mMapView.getOverlays().clear();
		mMapView.refresh();

	}

	/**
	 * 添加所有标记
	 */
	public void addAllMarker() {
		// initApplication app = (initApplication) getApplication();
		List<Eshop> list = app.getList();
		mMapView.getOverlays().clear();
		MyOverlay ov = new MyOverlay(getResources().getDrawable(R.drawable.icon_mark), mMapView);

		for (Eshop content : list) {
			int latitude = (int) (content.getLatitude() * 1E6);
			int longitude = (int) (content.getLongitude() * 1E6);
			Drawable d = getResources().getDrawable(R.drawable.icon_mark);
			OverlayItem item = new OverlayItem(new GeoPoint(latitude, longitude), content.getName(), content.getAddr());
			item.setMarker(d);
			ov.addItem(item);
		}

		mMapView.getOverlays().add(ov);
		mMapView.refresh();
		// 如果定位成功，添加当前坐标点
		if (app.currlocation != null) {
			MyLocationOverlay myLocationOverlay = new MyLocationOverlay(mMapView);
			LocationData locData = new LocationData();
			// 手动将位置源置为天安门，在实际应用中，请使用百度定位SDK获取位置信息，要在SDK中显示一个位置，需要
			// 使用百度经纬度坐标（bd09ll）
			locData.latitude = app.currlocation.getLatitude();
			locData.longitude = app.currlocation.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = app.currlocation.getRadius();
			locData.direction = app.currlocation.getDerect();

			locData.direction = 2.0f;
			myLocationOverlay.setData(locData);
			mMapView.getOverlays().add(myLocationOverlay);
			mMapView.refresh();
		}

		// 江阴市政府的中心，无定位时的地图中心
		int cLat = 31925816;
		int cLon = 120292073;
		if (app.currlocation == null) {
			mMapView.getController().setCenter(new GeoPoint(cLat, cLon));
		} else if (list != null && list.size() >= 1) {
			Eshop c = list.get(0);
			int currLat = (int) (c.getLatitude() * 1E6);
			int currLon = (int) (c.getLongitude() * 1E6);
			mMapView.getController().setCenter(new GeoPoint(currLat, currLon));
		}
	}

	/**
	 * 地图覆盖物，用于显示标记
	 * 
	 */
	public class MyOverlay extends ItemizedOverlay {
		PopupOverlay pop = null;
		private int clickedTapIndex = -1;

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
			pop = new PopupOverlay(mMapView, new PopupClickListener() {
				@Override
				public void onClickedPopup(int index) {
					String name = list.get(clickedTapIndex).getName();
					Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
				}

			});
		}

		@Override
		protected boolean onTap(int index) {
			final List<Eshop> list = InitApplication.getInstance().getList();
			OverlayItem item = getItem(index);
			clickedTapIndex = index;
			if (index >= list.size()) {
				// 点击自己位置marker，不做任何处理
				return true;
			}
			View popview = LayoutInflater.from(context).inflate(R.layout.marker_pop, null);
			TextView tveshop_name = (TextView) popview.findViewById(R.id.tv_pop_eshop_name);
			TextView tveshop_address = (TextView) popview.findViewById(R.id.tv_pop_eshop_address);

			String eshop_name = list.get(index).getName();
			String eshop_addres = list.get(index).getAddr();
			tveshop_name.setText(eshop_name);
			tveshop_address.setText(eshop_addres);
			pop.showPopup(ZyUnit.getBitmapFromView(popview), item.getPoint(), 50);

			super.onTap(index);
			return false;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mapView) {
			if (pop != null) {
				pop.hidePop();
			}
			super.onTap(pt, mapView);
			return false;
		}

	}
	

}
